<template>
  <div>
    <div class="bg">
      <div class="font24 bolder mb-20">轮播图设置</div>
      <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileChange"
          accept="image/*"
          multiple
      >

      <!-- 图片列表 -->
      <div class="image-list">
        <div
            v-for="(item, index) in imageList"
            :key="item.id"
            class="image-item"
        >
          <img :src="item.url" class="avatar">
          <div class="delete-btn" @click="deleteImage(index)">×</div>
        </div>

        <!-- 上传按钮（最多5张） -->
        <div
            v-if="imageList.length < 5"
            class="upload-btn"
            @click="addPic"
        >
          <i class="el-icon-plus"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageList: [], // 存储图片数组
      uploadIndex: 0 // 用于生成唯一id
    }
  },
  methods: {
    addPic() {
      this.$refs.fileInput.click();
    },

    handleFileChange(e) {
      const files = Array.from(e.target.files);
      if (files.length === 0) return;

      // 限制最多5张
      const remain = 5 - this.imageList.length;
      const addFiles = files.slice(0, remain);

      addFiles.forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.imageList.push({
            id: this.uploadIndex++,
            url: e.target.result
          });
        };
        reader.readAsDataURL(file);
      });

      e.target.value = '';
    },

    deleteImage(index) {
      this.imageList.splice(index, 1);
    }
  }
}
</script>

<style scoped lang="scss">
.bg{
  padding: 20px;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  width: 148px;
  height: 148px;
  position: relative;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);

  .avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .delete-btn {
    position: absolute;
    right: 5px;
    top: 5px;
    width: 20px;
    height: 20px;
    background: rgba(0,0,0,0.5);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background: #ff4444;
    }
  }
}

.upload-btn {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8c939d;
  font-size: 28px;
  cursor: pointer;

  &:hover {
    border-color: #409EFF;
  }
}
</style>